<template>
  <div class="page-card h-full">
    <div>
      <el-button @click="dialogVisible = true" type="primary"> 上传图片 </el-button>
    </div>

    <el-dialog v-model="dialogVisible" title="上传" style="background-color: #fff">
      <div>
        <el-upload
          class="upload-demo"
          drag
          multiple
          :auto-upload="false"
          v-model:file-list="fileList"
        >
          <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          <div class="el-upload__text">Drop file here or <em>click to upload</em></div>
          <template #tip>
            <div class="el-upload__tip">jpg/png files with a size less than 500kb</div>
          </template>
        </el-upload>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="tsrue()"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
    <div>
      <el-table
        :data="tableData"
        style="width: 100%"
        height="700px"
        v-loading="loading"
        element-loading-text="加载中..."
      >
        <el-table-column type="index" width="100" label="序号" />
        <el-table-column prop="time" label="上传时间" />
        <el-table-column prop="path" label="图片">
          <template #default="scope">
            <el-image
              style="width: 100px; height: 100px"
              :src="scope.row.path"
              :preview-src-list="[scope.row.path]"
              :zoom-rate="1.2"
              :max-scale="7"
              :min-scale="0.2"
              :initial-index="4"
              fit="cover"
              preview-teleported="true"
            />
            <!-- <el-button type="primary" link><a @click="goLook(scope.row)">查看</a> </el-button> -->
          </template>
        </el-table-column>
        <el-table-column prop="type" label="名称">
          <template #default="scope">
            {{ getFileNameFromPath(scope.row.path) }}
            <!-- {{ scope.row.path.replace('http://wtplug.oss-cn-hangzhou.aliyuncs.com/', '') }} -->
          </template>
        </el-table-column>
        <el-table-column prop="type" label="操作" width="200">
          <template #default="scope">
            <!-- <el-button type="primary" size="small">修改</el-button> -->

            <el-popover placement="bottom" :width="10" trigger="click" :visible="scope.row.visible">
              <el-button type="danger" size="small" @click="scope.row.visible = false"
                >取消</el-button
              >
              <el-button type="primary" size="small" @click="del(scope.row)">确定</el-button>
              <template #reference>
                <el-button
                  class="m-2"
                  type="danger"
                  size="small"
                  @click="scope.row.visible != scope.row.visible"
                  >删除</el-button
                >
              </template>
            </el-popover>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        style="float: right; margin-top: 20px"
        :page-sizes="[10, 20, 30, 40, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <el-dialog v-model="dialogVisibles" :show-close="false">
      <el-image
        style="margin: 40px"
        :src="image"
        :zoom-rate="1.2"
        :max-scale="7"
        :min-scale="0.2"
        :initial-index="4"
        fit="cover"
      />
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
const loading = ref(false);
import { ref, onMounted } from 'vue';
import { ElMessageBox } from 'element-plus';
import { UploadFilled } from '@element-plus/icons-vue';
import { ossBordSts, material, materialget, materialdelete } from '@/api/home';
// const OSS = import('ali-oss');
import OSS from 'ali-oss';
import moment from 'moment';
const pages = ref(10);
const handleSizeChange = (val) => {
  // alert(val);
  pages.value = val;
  getList();
};
// const { tableData, page, loading, resetParams, getList, handleCurrentChange, handleSizeChange } =
//   useTable({
//     apiFn: getAgentsUserListApi,
//     params: searchForm
//   });
const dialogVisibles = ref(false);
const image = ref('');
const datas = ref([]);
const total = ref(0);
const page = ref(1);
const formattedDate = ref('');
const handleCurrentChange = (val) => {
  page.value = val;
  console.log(page.value);
  getList();
};
const getFileNameFromPath = (path) => {
  const lastSlashIndex = path.lastIndexOf('/');
  if (lastSlashIndex !== -1) {
    return path.slice(lastSlashIndex + 1);
  }
  // 如果路径中没有 '/', 则返回整个路径
  return path;
};
const del = (row) => {
  row.visible = false;
  console.log(row._id);
  materialdelete(row._id).then((res) => {
    console.log('res', res);
    getList();
  });
};
onMounted(() => {
  loading.value = true;
  const currentDate = new Date();
  const year = currentDate.getFullYear();
  const month = String(currentDate.getMonth() + 1).padStart(2, '0'); // 使用padStart来确保月份是两位数
  formattedDate.value = `${year}-${month}`;
  console.log('formattedDate', formattedDate.value);
  ossBordSts().then((res) => {
    datas.value = res.data;
    console.log('res', datas.value);
  });
  getList();
});
const tableData = ref([]);
const goLook = (row) => {
  dialogVisibles.value = true;
  image.value = row.path;
  // window.location.assign(row.path);
};
const getList = () => {
  loading.value = true;
  materialget({
    page: page.value,
    pageSize: pages.value,
    type: 1
  }).then((res) => {
    loading.value = false;

    res.data.list.map((item, index) => {
      item.time = moment(item.createTime).format('YYYY-MM-DD');
    });
    total.value = res.data.total;
    tableData.value = res.data.list;
    console.log('resres:', tableData.value);
  });
};
const dialogVisible = ref(false);
const fileList = ref([]);
const tsrue = () => {
  loading.value = true;
  console.log(fileList.value);
  const list = [];
  const client = new OSS({
    accessKeyId: datas.value.AccessKeyId,
    accessKeySecret: datas.value.AccessKeySecret,
    stsToken: datas.value.SecurityToken,
    region: 'oss-cn-hangzhou',
    bucket: 'wtplug'
  });
  const promises = fileList.value.map((item, index) => {
    const fileName = `shopImage/border/${formattedDate.value}/` + item.name;
    return client
      .put(fileName, item.raw)
      .then((res) => {
        return material([
          {
            type: 1,
            path: res.url
          }
        ]).then((materialRes) => {});
      })
      .catch((err) => {
        console.error('Upload failed:', err);
      });
  });
  Promise.all(promises)
    .then((results) => {
      console.log('All uploads and material operations completed', results);
      getList();
    })
    .catch((err) => {
      loading.value = false;
      console.error('An error occurred during uploads or material operations:', err);
    });
  console.log('list', list);
  fileList.value = [];
  dialogVisible.value = false;
};
</script>
<style>
/* .el-dialog__header {
  padding: 0;
}
.el-dialog {
  --el-dialog-bg-color: none;
  --el-dialog-box-shadow: var(--el-dialog-bg-color);
} */
</style>